import { defineStore } from 'pinia'

export const useCacheStore = defineStore('cache', {
    state: () => ({
        // 需要缓存的组件名称列表
        cacheList: ['Home', 'user'],
        // 可以添加其他缓存相关的状态
        scrollPositions: {}, // 存储页面滚动位置
        pageStates: {} // 存储页面状态
    }),

    getters: {
        // 获取缓存列表
        getCacheList: (state) => state.cacheList,

        // 判断组件是否需要缓存
        shouldCache: (state) => (name) => state.cacheList.includes(name),

        // 获取页面滚动位置
        getScrollPosition: (state) => (name) => state.scrollPositions[name] || 0,

        // 获取页面状态
        getPageState: (state) => (name) => state.pageStates[name] || {}
    },

    actions: {
        // 添加缓存
        addCache(name) {
            if (!this.cacheList.includes(name)) {
                this.cacheList.push(name)
            }
        },

        // 移除缓存
        removeCache(name) {
            const index = this.cacheList.indexOf(name)
            if (index > -1) {
                this.cacheList.splice(index, 1)
                // 同时清除相关的状态
                this.clearPageState(name)
            }
        },

        // 清除所有缓存
        clearCache() {
            this.cacheList = []
            this.scrollPositions = {}
            this.pageStates = {}
        },

        // 保存页面滚动位置
        saveScrollPosition(name, position) {
            this.scrollPositions[name] = position
        },

        // 保存页面状态
        savePageState(name, state) {
            this.pageStates[name] = {
                ...this.pageStates[name],
                ...state
            }
        },

        // 清除页面状态
        clearPageState(name) {
            delete this.scrollPositions[name]
            delete this.pageStates[name]
        }
    }
})
